<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="cn">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>用户管理表格</title>

    <link href="${basePath!}/static/layui/css/layui.css" type="text/css" media="screen" rel="stylesheet"/>
    <!-- jquery插件包-必要 -->
    <!-- 这个是所有jquery插件的基础，首先第一个引入 -->
    <script src="${basePath!}/static/js/jquery.min.js" type="text/javascript"></script>
    <script src="${basePath!}/static/layui/layui.js" type="text/javascript"></script>
    <base href="${basePath!}/">

</head>
<body>
<div class="layui-btn-group">
    <button class="layui-btn" lay-event="add" id="add">增加</button>
</div>

<table id="list" lay-filter="operations"></table>

<#--↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓add↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓-->
<#--带有 class="layui-fluid" 的容器中，那么宽度将不会固定，而是 100% 适应-->
<div id="adddiv" hidden="" class="layui-fluid" style="margin: 15px;">
    <form class="layui-form" action="" id="addfrom">
        <#--<label hidden="true" id="editlabelid"></label>-->
        <#--<input id="username" name="username" value="" hidden/>-->
        <div class="layui-form-item">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-block">
                <input type="text" id="username" name="username" lay-verify="username" autocomplete="off" placeholder="请输入用户名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
            <input type="password" id="password" name="password" lay-verify="password" autocomplete="off" placeholder="请输入密码" class="layui-input">
        </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">地址</label>
            <div class="layui-input-block">
                <input type="text" id="address" name="address" autocomplete="off" placeholder="请输入地址" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input type="text" id="email" name="email" autocomplete="off" placeholder="请输入邮箱" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-block">
                <input type="text" id="phone" name="phone" autocomplete="off" placeholder="请输入电话" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="text" id="sex" name="sex" autocomplete="off" placeholder="性别" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-block">
                <input type="text" id="realName" name="realName" autocomplete="off" placeholder="请输入真实姓名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="addsubmit">立即提交</button>
                <button id="reset" type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>

    </form>
</div>
<#--↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑add↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑-->

<#--↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓为用户设置角色↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓-->

<#--带有 class="layui-fluid" 的容器中，那么宽度将不会固定，而是 100% 适应-->
<div hidden="" id="setroledivid" class="layui-fluid" style="margin: 15px;">
    <form class="layui-form" action="" id="setroleformid">
    </form>
</div>
<#--↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑-->


</body>
<script type="text/javascript">

    var layerid;//当前弹层id;这个id可以定义多个，主要的目的是为了在回调函数关闭弹层时使用的
    layui.use(['layer','form', 'table'], function(){
        var layer = layui.layer,
                table = layui.table,
                $ = layui.$,
                form = layui.form;

        table.render({
            elem: '#list',
            id: 'listReload',
            height: 500,
            url: 'admin/user/list',
            method:'post',
            page: true, //开启分页
            cols: [[ //表头
                {title: '序号', width:80, align: 'center',
                    templet: function(d){
                        return d.LAY_TABLE_INDEX + 1;
                    }},
                {field: 'username', title: '管理账号', sort: true, align : 'center'},
                {field: 'realName', edit: 'text', title: '真实姓名', align : 'center', width : 100},
                {field: 'sex', edit: 'text', title: '性别', align : 'center', width : 80},
                {field: 'phone', edit: 'text', title: '电话', align : 'center', width : 150},
                {field: 'email', edit: 'text', title: '邮箱', align : 'center'},
                {field: 'address', edit: 'text', title: '地址'},
                {field: 'roles', title: '角色',
                    templet: function(d){
                        var userRole;
                        var result = '';
                        for (userRole in d.roles){
                            if (result == ''){
                                result = d.roles[userRole].name;
                            }else{
                                result = result + '，' + d.roles[userRole].name;
                            }

                        }
                        return result;
                    }
                },
                {field: 'createTime', title: '创建时间', align : 'center', width : 250,
                    templet: function(d){
                        var time = new Date(d.createTime);
                        var year = time.getFullYear();
                        var month = (time.getMonth() + 1) > 9 ? (time.getMonth() + 1) : '0' + (time.getMonth() + 1);
                        var date = time.getDate() > 9 ? time.getDate() : '0' + time.getDate();
                        var hours = time.getHours() > 9 ? time.getHours() : '0' + time.getHours();
                        var minutes = time.getMinutes() > 9 ? time.getMinutes() : '0' + time.getMinutes();
                        var seconds = time.getSeconds() > 9 ? time.getSeconds() : '0' + time.getSeconds();
                        return year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
                    }},
                {fixed: 'right',
                    width:200,
                    align:'center',
                    toolbar: '#userOperations'}
            ]],
            response: {
                statusName: 'code',
                statusCode: 200,
                msgName: 'msg',
                countName: 'count',
                dataName: 'data',
            }
        });

        //监听工具条
        table.on('tool(operations)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            if(layEvent === 'setrole'){ //查看setroledivid
                //获得当前用户已经拥有的角色集合和未拥有的角色集合，并组装表单的复选按钮
                var username = data.username;
                $.ajax({
                    type: "POST",
                    url:"admin/user/role/selectUserByUsername",
                    data:{username:username},
                    async: false,
                    error: function(request) {
                        layer.alert("与服务器连接失败/(ㄒoㄒ)/~~");
                    },
                    success: function(data) {
                        if(data.code=='500'){
                            layer.alert(data.msg);
                            return false;
                        }
                        if(data.code=='200'){
                            var roles = data.data;

                            var html=[];
                            var strs="";
                            $.each(roles, function (n, value) {//n从0开始自增+1；value为每次循环的单个对象
                                strs+='<input type="checkbox" name="role" title="'+value.name+'" value="'+value.id+'" ' + value.checked + '>';
                            });
                            html.push(strs);
                            document.getElementById('setroleformid').innerHTML = html.join('');
                            layui.form.render(); //更新全部

                            layerid = layer.open({//开启表单弹层
                                skin: 'layui-layer-molv',
                                area:'60%',
                                type: 1,
                                title:'编辑角色',
                                btn: ['确定', '取消'],//定义两个按钮，是和否
                                shadeClose:true,
                                content: $('#setroledivid'),  //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                                yes : function(index, layero) {//点击是时候的回调

                                    // 获取所有已选中状态
                                    var checkeds = $('input[type=checkbox]:checked');
                                    var roleIds = '';
                                    for (var i=0; i<checkeds.length; i++){
                                        if (i != 0){
                                            roleIds += ',';
                                        }
                                        roleIds += checkeds.get(i).value;
                                    }

                                    $.ajax({
                                        type: "POST",
                                        url:"admin/user/role/userEditoyRoles",
                                        data:{username: username,
                                            roleIds: roleIds},
                                        async: false,
                                        error: function(request) {
                                            layer.alert("与服务器连接失败/(ㄒoㄒ)/~~");
                                        },
                                        success: function(data) {
                                            if(data.code=='500'){
                                                layer.alert("用户绑定角色不能为空");
                                                return false;
                                            }
                                            if (data.code == '200'){
                                                //打开成功消息提示
                                                layer.open({
                                                    skin: 'layui-layer-molv',
                                                    content: '角色修改成功！',
                                                    btn:['确定'],
                                                    shadeClose:true,
                                                    end: function(){
                                                        // 关闭弹窗
                                                        layer.close(layerid);//消息提示结束后回调，关闭上一级新建表单所在弹层
                                                        $(".layui-laypage-btn")[0].click();
                                                    }
                                                });

                                            }
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
            } else if(layEvent === 'del'){ //删除
                layer.open({
                    skin: 'layui-layer-molv',
                    content: '请确定是否真的要删除昵称为'+data.username+'的记录?',
                    btn: ['确定', '取消'],//定义两个按钮，是和否
                    yes: function(index, layero){//点击是时候的回调
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                        $.ajax({
                            type: "POST",
                            url:"admin/user/delete",
                            data:{username:data.username},
                            async: false,
                            error: function(request) {
                                layer.alert("与服务器连接失败/(ㄒoㄒ)/~~");
                            },
                            success: function(data) {
                                if(data.code==500){
                                    layer.alert(data.msg);
                                }
                                if(data.code==200){
                                    //打开成功消息提示
                                    layer.open({
                                        skin: 'layui-layer-molv',
                                        content: '删除成功！',
                                        btn:['确定'],
                                        shadeClose:true,
                                        end: function(){
                                            layer.close(layerid);//消息提示结束后回调，关闭上一级新建表单所在弹层
                                            $(".layui-laypage-btn")[0].click();
                                        }
                                    });

                                }
                            }
                        });
                    }
                });
            } else if(layEvent === 'save'){ //保存编辑
                data.createTime = toDate(data.createTime);
                layer.open({
                    skin: 'layui-layer-molv',
                    content: '请确定是否真的要编辑昵称为'+data.username+'的记录?',
                    btn: ['确定', '取消'],//定义两个按钮，是和否
                    yes: function(index, layero){//点击是时候的回调
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                        $.ajax({
                            type: "POST",
                            url:"admin/user/update",
                            data:data,
                            async: false,
                            error: function(request) {
                                layer.alert("与服务器连接失败/(ㄒoㄒ)/~~");
                            },
                            success: function(res) {
                                if(res.code==500){
                                    layer.alert(res.msg);
                                }
                                if(res.code==200){
                                    //打开成功消息提示
                                    layer.open({
                                        skin: 'layui-layer-molv',
                                        content: '编辑成功！',
                                        btn:['确定'],
                                        shadeClose:true,
                                        end: function(){
                                            layer.close(layerid);//消息提示结束后回调，关闭上一级新建表单所在弹层
                                            $(".layui-laypage-btn")[0].click();
                                        }
                                    });

                                }
                            }
                        });
                    }
                });
            }
        });

        //添加按钮点击事件
        $("#add").click(function () {
            $("#reset").click();//重置表单(新建时在进入表单前要重置一下表单的内容，不然表单打开后会显示上一次的表单的内容。这里调用表单中重置按钮的点击方法来重置)
            addlayer = layer.open({//开启表单弹层
                skin: 'layui-layer-molv',
                area:'60%',
                type: 1,
                title:'新建角色',
                shadeClose:true,
                content: $('#adddiv') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
        });

        //监听add 提交
        form.on('submit(addsubmit)', function(data) {
            $.ajax({
                type: "POST",
                url:"admin/user/save",
                data:$('#addfrom').serialize(),
                async: false,
                error: function(request) {
                    layer.alert("与服务器连接失败/(ㄒoㄒ)/~~");
                },
                success: function(data) {
                    if(data.code == 500){
                        layer.alert(data.msg);
                    }
                    if(data.code == 200){
                        layer.open({
                            skin: 'layui-layer-molv',
                            content: '操作成功！',
                            btn:['确定'],
                            shadeClose:true,
                            end: function(){
                                //消息提示结束后回调，关闭上一级 新建or编辑 表单所在弹层
                                layer.closeAll();
                                $(".layui-laypage-btn")[0].click();
                            }
                        });

                    }
                }
            });
            return false;
        });

        //时间戳的处理，将字符串转为date对象，以方便后台接收
        var DATE_REGEXP = new RegExp("(\\d{4})-(\\d{2})-(\\d{2})([T\\s](\\d{2}):(\\d{2}):(\\d{2})(\\.(\\d{3}))?)?.*");
        function toDate(dateString){
            if(DATE_REGEXP.test(dateString)){
                var timestamp = dateString.replace(DATE_REGEXP, function($all,$year,$month,$day,$part1,$hour,$minute,$second,$part2,$milliscond){
                    var date = new Date($year, $month,$day, $hour||"00", $minute||"00", $second||"00", $milliscond||"00");
                    return date.getTime();
                });
                var date = new Date();
                date.setTime(timestamp);
                return date;
            }
            return null;
        }

    });

</script>

<script type="text/html" id="userOperations">
    <a class="layui-btn layui-btn-xs" lay-event="setrole" id="setrole">角色</a>
    <a class="layui-btn layui-btn-xs" lay-event="save" id="save">保存</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" id="del">删除</a>
</script>
</html>